package br.com.devteam.base.converter;

import java.text.ParseException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.swing.text.MaskFormatter;

import br.com.devteam.base.validator.TelefoneValidator;

@FacesConverter(value = "TelefoneConverter")
public class TelefoneConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {

		if (arg2 != null && TelefoneValidator.validate(arg2)) {
			arg2 = arg2.replace("(", "").replace(")", "").replace(" ", "")
					.replace("-", "");
		}

		return arg2;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

		if (arg2 != null) {

			String mascara = "";

			if (arg2.toString().length() == 11) {
				mascara = "(##) ####-#####";
			} else if (arg2.toString().length() == 10) {
				mascara = "(##) ####-####";
			}

			MaskFormatter formatter = null;
			try {
				formatter = new MaskFormatter(mascara);
				formatter.setValueContainsLiteralCharacters(false);

				return formatter.valueToString(arg2);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

}
